package com.example.slice_simple;

import static java.lang.Math.min;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Message;
import android.widget.ImageView;
import android.widget.TextView;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.util.Base64;

/**
 * 和渲染服务器通信的线程类，接收视频数据
 */

public class ConnectSer{
    private boolean isSlice = false;
    private ConnectSlice cs = null;
    private final static String SEND_IP = "222.20.75.49";  //发送IP //10.21.179.204  192.168.1.108
    private final static int SEND_PORT = 8080;               //发送端口号
    private final static int RECV_POR = 8899;               //接收端口号
    private InetAddress serverAddr;

    private ImageView imgShow;// 图像显示
    private ReceiveHandler receiveHandler = new ReceiveHandler();
    private SendHandler sendHandler = new SendHandler();

    class ReceiveHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            imgShow.setImageBitmap(bp);
//            System.out.println("已更新图片");
        }
    }
    class SendHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
        }
    }
    Bitmap bp;


    public void init(ImageView i){
        imgShow = i;
    }

    public static byte[] readStream(InputStream inStream) throws Exception{
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[65536];
        int len = 0;
        while( (len=inStream.read(buffer)) != -1){
            outStream.write(buffer, 0, len);
        }
        outStream.close();
        inStream.close();
        return outStream.toByteArray();
    }

    public void recFile(){
        try {
            serverAddr = InetAddress.getByName(SEND_IP);
            new UdpSendThread().start(); // 发送向服务器的报文，等待服务器建立链接
            DatagramSocket socket = new DatagramSocket(RECV_POR);
            int frames_to_count = 20; //统计帧率
            double fps = 0;
            int cnt = 0;//当前接收了多少帧率
            long st = System.currentTimeMillis();
            System.out.println("开始等待接受报文，等待的port为");
            System.out.println(RECV_POR);
            while(true) {
                byte[] inBuf= new byte[300000];
                DatagramPacket inPacket = new DatagramPacket(inBuf,inBuf.length);
                //out.write(inPacket.getData());
                socket.receive(inPacket);
//                System.out.println("接受报文");
                if(!inPacket.getAddress().equals(serverAddr)){
                    throw new IOException("未知名的报文");
                }
//                ByteArrayInputStream in = new ByteArrayInputStream();
                try {
                    byte[] data= inPacket.getData();
                    int length = inPacket.getLength();
//                    System.out.println(length);
                    String rcvstr = new String(data, 0, length);
//                    System.out.println("data:" + rcvstr);
                    data = Base64.getDecoder().decode(rcvstr);
                    if(data!=null){
                        bp = BitmapFactory.decodeByteArray(data, 0, data.length);
                        cnt++;
                    }
                }catch (Exception e) {
                    e.printStackTrace();
                }
//                System.out.println("Tag:性能测试 成功接收报文" + "内容：" + bp.getWidth());
                receiveHandler.sendEmptyMessage(1);
                if(cnt == frames_to_count){
                    fps = cnt * 1000.0/ (System.currentTimeMillis() - st);
//                    System.out.println("CNT:" + cnt + " FPS:" + fps);
                    cnt = 0;
                    st = System.currentTimeMillis();
                    NetworkSlice.instance.setFps(String.valueOf(Math.round(fps)));
//                    System.out.println("更新帧率");
//                    System.out.println(fps);
                }
            }
        }
        catch (IOException e) {
            System.out.println("和渲染服务器通信失败");
            System.out.println(e);
        }
    }

    class UdpSendThread extends Thread{
        @Override
        public void run() {
            try {
                serverAddr = InetAddress.getByName(SEND_IP);
                DatagramSocket socket = new DatagramSocket(RECV_POR - 1); //por-1发送一次，后面用por的接受
                byte[] buf = "Android Start video 720p30fps".getBytes();//1080p60fps 720p30fps
//                byte[] buf = "Android Start video withoutfps".getBytes();
                DatagramPacket outPacket = new DatagramPacket(buf, buf.length, serverAddr, SEND_PORT);
                socket.send(outPacket);
                socket.close();
                System.out.println("已发送报文，等待渲染视频传输");
//                sendHandler.sendEmptyMessage(1);
            } catch (IOException e) {
                System.out.println("和渲染服务器通信失败");
                System.out.println(e);
            }
        }
    }
}
//
//
//    public void recWithoutFps(){
//        try {
//            serverAddr = InetAddress.getByName(SEND_IP);
//            new UdpSendThread().start();
//            DatagramSocket socket = new DatagramSocket(RECV_POR);
////            //接收文件长度
////            byte[] filelen= new byte[4];
////            DatagramPacket lenPacket = new DatagramPacket(filelen,filelen.length);
////            socket.receive(lenPacket);
////            for(int i = 0; i < 4; ++i)
////                filelen[i] = filelen[3-i];
////            ByteBuffer firstLine = ByteBuffer.wrap(filelen);
////            int fileLen = firstLine.getInt(); // 得到文件长度
//
//            while(true) {
//                byte[] inBuf= new byte[1024];
//                DatagramPacket inPacket = new DatagramPacket(inBuf,inBuf.length);
//                //out.write(inPacket.getData());
//                socket.receive(inPacket);
//                if(!inPacket.getAddress().equals(serverAddr)){
//                    throw new IOException("未知名的报文");
//                }
//                ByteArrayInputStream in = new ByteArrayInputStream(inPacket.getData());
//                try {
//                    byte[] data=readStream(in);
//                    if(data!=null){
//                        bp = BitmapFactory.decodeByteArray(data, 0, data.length);
//                    }
//                }catch (Exception e) {
//                    e.printStackTrace();
//                }
////                bp = BitmapFactory.decodeStream(in); //暂时无法播放，寻找新的解码方式
////                System.out.println("Tag:性能测试 成功接收报文" + "内容：" + bp.getWidth());
//                receiveHandler.sendEmptyMessage(1);
//            }
//        }
//        catch (IOException e) {
//            System.out.println("和渲染服务器通信失败");
//            System.out.println(e);
//        }
//    }
